package com.area.controller;

import com.alibaba.fastjson.JSONArray;
import com.area.entity.SysArea;
import com.area.service.SysAreaService;
import com.area.util.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 1、导入sql
 * 2、调用 /getAreaByProvinceName 爬区政府省市区直接保存到数据库
 * @author WangPeiXi
 * @date 2022/5/23 16:19
 * @version V1.0.0
 */
@RestController
public class AreaController {

    @Autowired
    private SysAreaService sysAreaService;

    /**
     * 获取国家省市区的地址
     * 最新2021年
     * http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/
     */
    private String url = "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2021/index.html";
    /**
     * 生成省市区 4级 5级 一个省一个省做
     * @author WangPeiXi
     * @date 2022/7/7 17:52
     * @version V1.0.0
     * @param level  等级
     * @param provinceCode  省编码12位
     * @return null
     */
    @GetMapping("/generateArea")
    public String generateArea(Integer level,String provinceCode){
        if(null == level || 0 > level){
            return "请输入等级 1-5";
        }
        sysAreaService.generateArea(url,level,provinceCode);
        return "success";
    }

    /**
     * 查询三级树
     * @param pid
     * @return
     */
    @GetMapping("/getAdministrativeCode")
    public JSONArray getAdministrativeCode(@RequestParam(name="pid", defaultValue="0") String pid){
        List<SysArea> list = sysAreaService.list(Wrappers.<SysArea>lambdaQuery()
                .ne(SysArea::getLevel,4));
        return TreeUtil.parseTree(list,"id","pid","children",pid);
    }

}
